//
//  YDLoginViewModel.swift
//  YDReadFish
//
//  Created by 王允顶 on 2019/4/29.
//  Copyright © 2019年 wuyezhiguhun. All rights reserved.
//

import UIKit

enum YDLoginType {
    case Success
    case Error
}

class YDLoginViewModel: NSObject {

    
    lazy var userInfoLilst: NSArray = {
        var userArray = NSKeyedUnarchiver.unarchiveObject(withFile: self.filePath)
        if userArray != nil {
            return userArray as! NSArray
        } else {
            return NSArray()
        }
//        if let array: NSArray = NSKeyedUnarchiver.unarchiveObject(withFile: self.filePath) {
//            return array
//        } else {
//            return NSArray()
//        }
    }()
    
    lazy var filePath: String = {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "userInfoData"
        return path
    }()
}

extension YDLoginViewModel {
    
    /**
     * 是否显示注册按钮
     * @return true: 不显示  false: 显示
     */
    func registerButtonHidden() -> Bool {
        if self.userInfoLilst.count > 0 {
            return true
        } else {
            return false
        }
    }
    
    /**
     * 注册逻辑处理
     * @pram userName 用户名
     * @pram userPassword 密码
     * @return true: 注册成功  false: 注册失败
     */
    func registerUserInfo(userName: String, userPassword: String) -> Bool {
        for userInfo in self.userInfoLilst {
            if (userInfo as! YDUserInfo).userName == userName && (userInfo as! YDUserInfo).userPassword == userPassword {
                return false
            }
        }
        
        let userArray = NSMutableArray(array: self.userInfoLilst)
        let userInfo: YDUserInfo = YDUserInfo()
        userInfo.userName = userName
        userInfo.userPassword = userPassword
        
        userArray.add(userInfo)
        
        self.userInfoLilst = userArray.copy() as! NSArray
        
        return NSKeyedArchiver.archiveRootObject(userArray, toFile: self.filePath)
    }
    
    /**
     * 登录逻辑处理
     * @pram userName 用户名
     * @pram userPassword 密码
     * @return true: 登录成功  false: 登录失败
     */
    func loginUserInfo(userName: String, userPassword: String) -> Bool {
        for userInfo in self.userInfoLilst {
            if (userInfo as! YDUserInfo).userName == userName && (userInfo as! YDUserInfo).userPassword == userPassword {
                return true
            }
        }
        
        return false
    }
    
    
    
    /** 清除所有的注册信息 */
    func clearUserInfo() {
        if FileManager.default.fileExists(atPath: self.filePath) {
            try! FileManager.default.removeItem(atPath: self.filePath)
        }
        self.userInfoLilst = NSArray()
    }
}
